import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import cartApi from '@/api/cartApi.js'

export const useCartStore = defineStore('cart', () => {
	// 定义状态
	const hasToken = ref(false)
	const token = uni.getStorageSync('token');
	hasToken.value = !!token;
	const cartList = ref([]);
	const counponList = ref([]); // 优惠券列表，用于购物车页面展示优惠券信息。
	const cartTotal = ref(0)
	const cartCount = ref(0)
	const cartAmount = ref(0)
	const checkedAll = ref(false)
	let isFee = ref(0)
	let cartFee = ref(0)
	// 定义获取器（相当于 Vuex 的 Getters）
	const getCartCount = () => {
		let total = 0;
		let count = 0; // 购物车商品数量计数器，用于购物车页面展示购物车商品总数。
		let amount = 0;
		cartList.value.forEach(item => { // 遍历购物车列表，累加商品数量。
			item.list.forEach(subItem => {
				total += subItem.quantity;
				if (subItem.checked) {
					count += subItem.quantity;
					amount += subItem.quantity * parseFloat(subItem.sku.price);
				}
			})
		})
		cartTotal.value = total;
		cartCount.value = count; // 更新购物车商品总数。
		cartAmount.value = amount.toFixed(2);
	};

	const getCartList = () => {
		const token = uni.getStorageSync('token');
		if (!token) return;

		cartApi.list().then(res => {
			HFormate(res.data)

			let allCheck = true;
			cartList.value.forEach(v => {
				v.checked = true;
				v.list.forEach(subV => {
					v.checked = v.checked && subV.checked;
				})
				allCheck = allCheck && v.checked;
			});

			checkedAll.value = allCheck;

			getCartCount()
		}).catch(err => {
			console.error(err); // 处理错误情况，例如显示错误提示信息等。				
		})
	};
	getCartList()

	const HFormate = (arr) => {
		arr.forEach(item => {
			item.storeName = item.mallGood.tenantName;
			item.storeId = item.mallGood.tenantId;
		})
		const group = arr.reduce((prev, item) => {
			const key = item.storeId;
			if (!prev[key]) {
				prev[key] = {
					storeId: item.storeId,
					storeName: item.storeName,
					list: [],
					id: new Date().getTime()
				};
			}
			prev[key].list.push(item);
			return prev;
		}, {})
		cartList.value = Object.values(group).sort((a, b) => a.id - b.id);

		// 把sku提取到外层
		cartList.value.forEach(item => {
			item.list.forEach(subItem => {
				const item = subItem.mallGood.skuList.find(v => v.id == subItem.skuId)
				subItem.sku = {
					...item,
					...JSON.parse(item.attributeJson)
				}
			})
		})
	}

	const addCart = (data) => {
		cartApi.submit(data).then(res => {
			getCartList();
		})
	};

	// 返回状态和函数，以便在组件中使用
	return {
		hasToken,
		cartList,
		cartTotal,
		cartCount,
		cartAmount,
		isFee,
		cartFee,
		checkedAll,
		getCartList,
		addCart
	};
});